#ifndef DPI_C
#define DPI_C

#include <iostream>
#include <Python.h>
#include <svdpi.h>
#include <veriuser.h>
 
using namespace std;

int call_py(int a, int b)
{
	// 初始化python接口
	Py_Initialize();
	if(!Py_IsInitialized()){
		cout << "Python init fail" << endl;
		return 1;
	}

	// 设置python文件路径并读入
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('..')");
	PyObject* pModule = PyImport_ImportModule("alu");
	if(pModule == NULL)
	{
		cout <<"Module not found." << endl;
		return 1;
	}
 
	// 检索python函数
	PyObject* pFunc = PyObject_GetAttrString(pModule, "sum");
	if(!pFunc || !PyCallable_Check(pFunc))
	{
		cout <<"Function not found." << endl;
		return 1;
	}

	// 创建python元组，长度为2
	PyObject* pArgs = PyTuple_New(2);
	
	// 使用元组传入函数参数
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", a)); 
	PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", b)); 
	
	// 调用python函数
	PyObject* pReturn = PyEval_CallObject(pFunc, pArgs);
	
	// 接收python函数返回值
	int sum;
	PyArg_Parse(pReturn, "i", &sum);
	cout << "return result is " << sum << endl;
	
	// 结束python接口和Python/C API函数的所有初始化
	Py_Finalize();
} 

#ifdef __cplusplus
extern "C" {
#endif
	int do_call_py(int a, int b)
	{
		return call_py(a, b);
	}
#ifdef __cplusplus
}
#endif

#endif
